/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package adara.plugins.imagesave;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import adara.core.CoreRuntimeException;
import adara.plugins.Plugin;

/**
 * Plugin which implement the saving of the images.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public class ImageSavePlugin extends Plugin {
	
	private static final Logger logger = 
			Logger.getLogger(ImageSavePlugin.class);
	
	private File storage;
	private List<BufferedImage> images;

	@Override
	protected void update(BufferedImage image) {
		synchronized (images) {
			images.add(image);
		}
	}

	@Override
	public void init(int timegap, File storage) {
		if (logger.isTraceEnabled()) 
			logger.trace(getClass().getSimpleName() + " Initiated");
		
		this.storage = storage;
		this.images = new LinkedList<BufferedImage>();
	}

	@Override
	protected void process() {
		BufferedImage[] iarr = null; 
				
		synchronized (images) {
			iarr = images.toArray(new BufferedImage[images.size()]);
			images.clear();
		}
		
		if (logger.isTraceEnabled()) 
			logger.trace("Processing a bunch of " + iarr.length);
		
		for (BufferedImage image : iarr) {
			saveImage(image);
		}
				
	}
	
	private void saveImage(BufferedImage image) {
		File fimage = new File(this.storage.getAbsolutePath() 
				+ File.separator + System.currentTimeMillis() + ".png");
		
		try {
			ImageIO.write(image, "png", fimage);
		} catch (IOException e) {
			throw new CoreRuntimeException(
					"Could not save images to storage directory", e);
		}
		
		if (logger.isTraceEnabled()) 
			logger.trace("Image with name " + fimage.getName() + " saved!");
	}

}
